package com.wmlive.hhvideo.heihei.mainhome.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewStub;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.model.OSSRequest;
import com.wmlive.hhvideo.application.DCApplication;
import com.wmlive.hhvideo.common.GlobalParams;
import com.wmlive.hhvideo.common.base.BaseFragment;
import com.wmlive.hhvideo.common.navigator.Navigator;
import com.wmlive.hhvideo.common.ossutils.UpLoadInterface;
import com.wmlive.hhvideo.common.ossutils.UploadALiResultBean;
import com.wmlive.hhvideo.common.ossutils.UploadPresenter;
import com.wmlive.hhvideo.heihei.beans.opus.OpusPublishRequestBean;
import com.wmlive.hhvideo.heihei.db.manager.IMMessageDefaultDBManager;
import com.wmlive.hhvideo.heihei.db.manager.IMMessageUserDBManager;
import com.wmlive.hhvideo.heihei.discovery.activity.DiscoveryActivity;
import com.wmlive.hhvideo.heihei.discovery.activity.SearchMusicVideoActivity;
import com.wmlive.hhvideo.heihei.login.AccountUtil;
import com.wmlive.hhvideo.heihei.mainhome.presenter.HomePresenter;
import com.wmlive.hhvideo.heihei.mainhome.presenter.UserInfoCallback;
import com.wmlive.hhvideo.heihei.personal.PersonalFragment;
import com.wmlive.hhvideo.heihei.recordvideo.DyUIAPICallbackImpl;
import com.wmlive.hhvideo.utils.KLog;
import com.wmlive.hhvideo.utils.ToastUtil;
import com.wmlive.hhvideo.utils.imageloader.GlideLoader;
import com.wmlive.hhvideo.utils.preferences.SPUtils;
import com.wmlive.hhvideo.widget.MainBottomTabView;
import com.wmlive.hhvideo.widget.MainTopTabView;
import com.wmlive.hhvideo.widget.OnMainTabClickListener;

import java.lang.ref.WeakReference;

import butterknife.BindView;
import cn.wmlive.hhvideo.R;
import cn.wmlive.hhvideo.rxbuslib.RxBus2;
import cn.wmlive.hhvideo.rxbuslib.RxBusSubscribe;
import cn.wmlive.hhvideo.rxbuslib.ThreadMode;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;


/**
 * Created by lsq on 7/4/2017.
 * 首页Fragment
 */

public class HomeFragment extends BaseFragment<HomePresenter> implements
        OnMainTabClickListener,
        UpLoadInterface,
        UserInfoCallback,
        HomePresenter.IHomeView {

    private static final String KEY_SHOW_GUIDE = "key_show_guide";
    public static final String KEY_LATEST_GET_DISCOVERY_MSG = "key_latest_get_discovery_msg";
    @BindView(R.id.mbTopTabs)
    MainTopTabView mbTopTabs;
    @BindView(R.id.mbBottomTabs)
    MainBottomTabView mbBottomTabs;
    @BindView(R.id.flContainer)
    FrameLayout flContainer;
    @BindView(R.id.vs_main_guide)
    ViewStub vsMainGuide;
    @BindView(R.id.layout_upload_view)
    View layout_upload_view;
    @BindView(R.id.iv_upload_icon)
    ImageView iv_upload_icon;
    @BindView(R.id.iv_upload_icon_mask)
    ImageView iv_upload_icon_mask;
    @BindView(R.id.pb_upload_bar)
    ProgressBar pb_upload_bar;
    @BindView(R.id.tv_upload_num)
    TextView tv_upload_num;

    ImageView ivMainGuide;
    RelativeLayout rlGuide;
    private static final String TAG_ATTENTION = "tag_attention";
    private static final String TAG_RECOMMEND = "tag_recommend";
    private static final String TAG_EXPLOSION = "tag_explosion";
    private static final String TAG_PERSONAL = "tag_personal";
    private static final int MSG_GET_DISCOVERY_MESSAGE = 10;//请求发现的消息数量

    //上传作品
    private int uploadType = 0;//(1:上传视频  2：上传图片   3：上传动图 ，4 ：业务)
    private UploadPresenter uploadPresenter;
    private RefreshUploadHandler RefreshUploadHandler;
    private int iCurrentUploadProgress = -1;//上传的当前进度
    private int iRefreshUploadHandlerType = -1;//当前的操作类型(0：操作失败  1:开始导出  2 ：导出进度  3：导出成功  4：上传开始 5：上传进度 6：上传进度 7：上传完成  )
    private OpusPublishRequestBean opusPublishRequestBean;//上传作品信息类

    public static int currentTabPosition = 1;  //当前tab的位置
    private int topTabPosition = 1;//顶部3个tab的位置
    private UserInfoCallback userInfoCallback;//获取用户信息的回调
    private FragmentManager fragmentManager;

    private AttentionFragmentNew attentionFragmentNew;
    private RecommendFragmentNew recommendFragmentNew;
    private ExplosionFragment explosionFragment;
    private PersonalFragment personalFragment;

    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    @Override
    protected int getBaseLayoutId() {
        return R.layout.fragment_home;
    }


    @Override
    protected HomePresenter getPresenter() {
        return new HomePresenter(this);
    }

    //定时轮询发现的消息
    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_GET_DISCOVERY_MESSAGE:
                    presenter.getDiscoveryMessage(SPUtils.getLong(getActivity(), KEY_LATEST_GET_DISCOVERY_MSG, 0L));
                    break;
            }
        }
    };

    @Override
    protected void onSingleClick(View v) {
        if (v.getId() == R.id.iv_main_guide) {
            SPUtils.putBoolean(getActivity(), KEY_SHOW_GUIDE, true);
            if (vsMainGuide != null) {
                vsMainGuide.setVisibility(View.GONE);
            }
        }
    }

    @Override
    protected void onInvisible() {
        super.onInvisible();
        if (topTabPosition == 0 && null != attentionFragmentNew) {
            attentionFragmentNew.pausePlay();
        } else if (topTabPosition == 1 && null != recommendFragmentNew) {
            recommendFragmentNew.pausePlay();
        }
    }

    @Override
    protected void onVisible() {
        super.onVisible();
        resumePlay();
        updateDateBell();
    }

    public void resumePlay() {
        if (topTabPosition == 0 && null != attentionFragmentNew) {
            attentionFragmentNew.resumePlay();
        } else if (topTabPosition == 1 && null != recommendFragmentNew) {
            recommendFragmentNew.resumePlay();
        }
    }

    @Override
    protected void initData() {
        super.initData();
        RxBus2.get().register(this);
        currentTabPosition = 1;
        initFragment();
        showGuide();
        iCurrentUploadProgress = -1;
        RefreshUploadHandler = new RefreshUploadHandler(this);
        initDyUIAPICallbackImpInfo();
        showTVUploadProgress(false);
        mbTopTabs.showBell(true);
        presenter.getDiscoveryMessage(SPUtils.getLong(getActivity(), KEY_LATEST_GET_DISCOVERY_MSG, 0L));
        updateDateBell();
    }

    private void initFragment() {
        mbTopTabs.setTabClickListener(this);
        mbBottomTabs.setTabClickListener(this);
        mbTopTabs.setSelect(1);
        mbBottomTabs.setSelect(0);
        recommendFragmentNew = RecommendFragmentNew.newInstance(RecommendFragmentNew.TYPE_RECOMMEND);
        fragmentManager = getChildFragmentManager();
        fragmentManager.beginTransaction()
                .add(R.id.flContainer, recommendFragmentNew, TAG_RECOMMEND)
                .commit();
        recommendFragmentNew.setUserInfoCallback(this);
    }

    @Override
    public boolean onHomeClick() {
        showFragment(topTabPosition);
        mbTopTabs.setVisibility(View.VISIBLE);
        if (topTabPosition != 2) {
            RxBus2.get().send(GlobalParams.EventType.TYPE_SCROLL, true);
        }
        showTVUploadProgress(topTabPosition == 2);
        return true;
    }

    @Override
    public boolean onFollowClick() {//关注页面
        if (isRecyclerIdle()) {
            if (AccountUtil.isLogin()) {
                if (attentionFragmentNew == null) {
                    attentionFragmentNew = AttentionFragmentNew.newInstance();
                    addFragment(attentionFragmentNew, TAG_ATTENTION);
                    attentionFragmentNew.setUserInfoCallback(this);
                } else {
                    showFragment(0);
                }
                topTabPosition = 0;
                attentionFragmentNew.getUserInfo(attentionFragmentNew.getUserId());
                RxBus2.get().send(GlobalParams.EventType.TYPE_SCROLL, true);
                showTVUploadProgress(false);
                return true;
            } else {
                showReLogin();
                return false;
            }
        } else {
            return false;
        }
    }

    @Override
    public boolean onRecommendClick() {//推荐页面
        if (isRecyclerIdle()) {
            showFragment(1);
            topTabPosition = 1;
            RxBus2.get().send(GlobalParams.EventType.TYPE_SCROLL, true);
            showTVUploadProgress(false);
            recommendFragmentNew.getUserInfo(recommendFragmentNew.getUserId());
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        updateDateBell();
    }

    @Override
    public boolean onLatestClick() {//最新页面
        if (isRecyclerIdle()) {
            if (explosionFragment == null) {
                explosionFragment = ExplosionFragment.newInstance();
                addFragment(explosionFragment, TAG_EXPLOSION);
            } else {
                showFragment(2);
            }
            topTabPosition = 2;
            RxBus2.get().send(GlobalParams.EventType.TYPE_SCROLL, false);
            showTVUploadProgress(true);
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean onMineClick() {//个人信息页面
        if (isRecyclerIdle()) {
            if (AccountUtil.isLogin()) {
                mbTopTabs.setVisibility(View.GONE);
                if (personalFragment == null) {
                    personalFragment = new PersonalFragment();
                    addFragment(personalFragment, TAG_PERSONAL);
                } else {
                    showFragment(3);
                }
                showTVUploadProgress(false);
                RxBus2.get().send(GlobalParams.EventType.TYPE_SCROLL, false);
                return true;
            } else {
                showReLogin();
                return false;
            }
        } else {
            return false;
        }
    }

    @Override
    public void onDiscoveryClick() {
        if (isRecyclerIdle()) {
            startActivity(new Intent(getActivity(), DiscoveryActivity.class));
            mbTopTabs.showDiscoverDot(false);
        }
    }

    @Override
    public void onPublishClick() {
        if (isRecyclerIdle()) {
            if (!AccountUtil.isLogin()) {
                showReLogin();
            } else {
                startActivity(new Intent(getActivity(), SearchMusicVideoActivity.class));
            }
        }
    }

    @Override
    public void onBellClick() {//进入铃铛页面
        if (isRecyclerIdle()) {
            Navigator.getInstance().navigateToBell(getActivity());
        }
    }

    @RxBusSubscribe(code = GlobalParams.RXBusCode.IM_NOTIFICATION_NEW_MSG, threadMode = ThreadMode.MAIN)
    public void receiveBellUpdateEvent() {
        updateDateBell();
    }

    /**
     * 更新铃铛状态
     */
    private void updateDateBell() {
        if (AccountUtil.isLogin()) {
            IMMessageUserDBManager userDBManager = IMMessageUserDBManager.getInstance(DCApplication.getDCApp());
            if (mbTopTabs != null) {
                mbTopTabs.showBellDot(userDBManager.getImUserEntryUnReadCount() > 0);
            }
        } else {
            IMMessageDefaultDBManager defaultDBManager = IMMessageDefaultDBManager.getInstance(DCApplication.getDCApp());
            if (mbTopTabs != null) {
                mbTopTabs.showBellDot(defaultDBManager.getImDefaultEntryUnReadCount() > 0);
            }
        }
    }

    private void addFragment(BaseFragment fragment, String tag) {
        showFragment(getFragmentPosition(tag));
        fragmentManager.beginTransaction()
                .add(R.id.flContainer, fragment, tag)
                .show(fragment)
                .commit();
        KLog.i("====#add fragment:" + fragment.getTag());
        switch (tag) {
            case TAG_ATTENTION:
                currentTabPosition = 0;
                break;
            case TAG_RECOMMEND:
                currentTabPosition = 1;
                break;
            case TAG_EXPLOSION:
                currentTabPosition = 2;
                break;
            case TAG_PERSONAL:
                currentTabPosition = 3;
                break;
        }
    }

    private void showFragment(int position) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        for (int i = 0; i < 4; i++) {
            Fragment fragment = fragmentManager.findFragmentByTag(getFragmentTag(i));
            if (null != fragment) {
                if (position != i) {
                    transaction.hide(fragment);
                    KLog.i("====#hide fragment:" + fragment.getTag());
                } else {
                    transaction.show(fragment);
                    KLog.i("====#show fragment:" + fragment.getTag());
                }
            }
        }
        transaction.commit();
        currentTabPosition = position;
    }

    private String getFragmentTag(int position) {
        switch (position) {
            case 0:
                return TAG_ATTENTION;
            case 1:
                return TAG_RECOMMEND;
            case 2:
                return TAG_EXPLOSION;
            case 3:
                return TAG_PERSONAL;
        }
        return null;
    }

    private int getFragmentPosition(String tag) {
        switch (tag) {
            case TAG_ATTENTION:
                return 0;
            case TAG_RECOMMEND:
                return 1;
            case TAG_EXPLOSION:
                return 2;
            case TAG_PERSONAL:
                return 3;
        }
        return 0;
    }

    private boolean isRecyclerIdle() {
        boolean isIdle = true;
        if (attentionFragmentNew != null) {
            isIdle = attentionFragmentNew.isRecyclerIdle();
            KLog.i("=====关注页面" + (isIdle ? "停止" : "在滚动"));
        }
        if (recommendFragmentNew != null) {
            KLog.i("=====推荐页面" + (recommendFragmentNew.isRecyclerIdle() ? "停止" : "在滚动"));
            isIdle = (isIdle && recommendFragmentNew.isRecyclerIdle());
        }
        return isIdle;
    }

    private void showGuide() {
        Observable.just(1)
                .subscribeOn(Schedulers.io())
                .map(new Function<Integer, Boolean>() {
                    @Override
                    public Boolean apply(Integer integer) throws Exception {
                        return SPUtils.getBoolean(getActivity(), KEY_SHOW_GUIDE, false);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            //hide
                            if (vsMainGuide == null) {
                                vsMainGuide = (ViewStub) findViewById(R.id.vs_main_guide);
                            }
                            vsMainGuide.setVisibility(View.GONE);
                        } else {
                            //show
                            if (vsMainGuide == null) {
                                vsMainGuide = (ViewStub) findViewById(R.id.vs_main_guide);
                            }
                            vsMainGuide.inflate();
                            ivMainGuide = (ImageView) findViewById(R.id.iv_main_guide);
                            ivMainGuide.setOnClickListener(HomeFragment.this);
                            GlideLoader.loadImage(R.drawable.icon_home_guide, ivMainGuide, R.drawable.icon_home_guide);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@NonNull Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                    }
                });
    }

    /**
     * 初始化第三方录制回调信息
     */
    private void initDyUIAPICallbackImpInfo() {
        uploadPresenter = new UploadPresenter(this);
        uploadPresenter.setmUpLoadInterface(this);
        DyUIAPICallbackImpl.getInstance().setContext(getActivity());
        DyUIAPICallbackImpl.getInstance().setmCurrentCallbackHandler(RefreshUploadHandler);
    }

    /**
     * 导出开始
     */
    private void exportVideoStart(Bundle mBundle) {
        String strShortVideoFirstImgPath = "";

        //获取部上传作品数据
        opusPublishRequestBean = new OpusPublishRequestBean();
        if (mBundle != null) {
            opusPublishRequestBean.setTitle(mBundle.getString("title"));
            opusPublishRequestBean.setTopic_id(mBundle.getLong("topic_id"));
            opusPublishRequestBean.setMusic_id(mBundle.getLong("music_id"));
            opusPublishRequestBean.setOpus_length(mBundle.getFloat("opus_length"));
            opusPublishRequestBean.setOpus_gif_cover("");
            opusPublishRequestBean.setOpus_gif_cover_sign("");
            opusPublishRequestBean.setAt_user_ids(null);
            strShortVideoFirstImgPath = mBundle.getString("shorvideo_first_image");
        }
        //加载图片
        GlideLoader.loadImage(strShortVideoFirstImgPath, iv_upload_icon, R.drawable.ic_photo_loading);
        //显示上传进度
        refreshExportProgress(0);
        showTVUploadProgress(true);
    }

    /**
     * 更新导出进度
     *
     * @param progress
     */
    private void refreshExportProgress(int progress) {
        if (progress > -1) {
            iCurrentUploadProgress = progress;
            if (iCurrentUploadProgress >= 97) {
                iCurrentUploadProgress = 97;
            }
            tv_upload_num.setText(String.valueOf(iCurrentUploadProgress) + "%");
        }
    }

    /**
     * 导出完成
     *
     * @param mBundle
     */
    private void exportVideoEnd(Bundle mBundle) {
        if (mBundle != null) {
            String strLoadVideoPath = mBundle.getString("UploadPath");
            //开始上传
            uploadType = 1;
            uploadPresenter.setStrUploadPath(strLoadVideoPath);
            uploadPresenter.getOSSTokenAndUploadInfo("opus", "mp4");
        }
    }

    /**
     * 刷新进度
     */
    private synchronized void refreshUploadProgress(int progress) {
        if (progress > -1) {
            iCurrentUploadProgress = iCurrentUploadProgress + progress;
            if (iCurrentUploadProgress >= 100) {
                iCurrentUploadProgress = 100;
            }
        }
        tv_upload_num.setText(String.valueOf(iCurrentUploadProgress) + "%");
    }


    /**
     * 上传完成
     */
    private void refreshUpdateFinish() {
        if (tv_upload_num != null) {
            iCurrentUploadProgress = -1;
            showTVUploadProgressUI(1);
        }
        DyUIAPICallbackImpl.getInstance().deletDraftBoxVideoInfo();
    }

    /**
     * 上传完成刷新UI
     */
    private void refreshUpdateFinishUI() {
        showTVUploadProgressUI(0);
        showToast(R.string.publish_succeed);
        mbTopTabs.showRLBellView();
    }

    /**
     * 上传错误
     */
    private void refreshUpdateError() {
        if (tv_upload_num != null) {
            iCurrentUploadProgress = -1;
            ToastUtil.showToast("上传作品失败，请到草稿箱中查看");
            showTVUploadProgressUI(0);
        }
        mbTopTabs.showRLBellView();
    }

    /**
     * @param type（0：全部隐藏 1：隐藏上传进度   2：全部显示）
     */
    private void showTVUploadProgressUI(int type) {
        if (type == 2) {
            iv_upload_icon.setVisibility(View.VISIBLE);
            iv_upload_icon_mask.setVisibility(View.VISIBLE);
            pb_upload_bar.setVisibility(View.VISIBLE);
            tv_upload_num.setVisibility(View.VISIBLE);
        } else if (type == 1) {
            iv_upload_icon.setVisibility(View.VISIBLE);
            iv_upload_icon_mask.setVisibility(View.GONE);
            pb_upload_bar.setVisibility(View.GONE);
            tv_upload_num.setVisibility(View.GONE);
            tv_upload_num.setText("0%");
        } else if (type == 0) {
            iv_upload_icon.setVisibility(View.GONE);
            iv_upload_icon_mask.setVisibility(View.GONE);
            pb_upload_bar.setVisibility(View.GONE);
            tv_upload_num.setVisibility(View.GONE);
            tv_upload_num.setText("0%");
        }
    }

    /**
     * 说服显示进度条
     *
     * @param visible
     */
    private void showTVUploadProgress(boolean visible) {
        if (visible && iCurrentUploadProgress >= 0) {
            layout_upload_view.setVisibility(View.VISIBLE);
            showTVUploadProgressUI(2);
            mbTopTabs.hideRLBellView();
        } else {
            layout_upload_view.setVisibility(View.INVISIBLE);
            mbTopTabs.showRLBellView();
        }
    }


    /**
     * 设置获取用户信息的回调
     *
     * @param userInfoCallback
     */
    public void setUserInfoCallback(UserInfoCallback userInfoCallback) {
        this.userInfoCallback = userInfoCallback;
    }

    @Override
    public void getUserInfo(long userId) {
        if (userInfoCallback != null) {
            userInfoCallback.getUserInfo(userId);
        }
    }


    @Override
    public void onGetDiscoveryMessage(boolean hasNew, int nextTime) {
        mbTopTabs.showDiscoverDot(hasNew);
        KLog.i("====收到Discovery的消息");
        if (handler != null) {
            handler.sendEmptyMessageDelayed(MSG_GET_DISCOVERY_MESSAGE, nextTime > 0 ? (nextTime * 1000) : 60000);
        }
    }

    /**
     * 刷新上传作品进度
     */
    private static class RefreshUploadHandler extends Handler {
        WeakReference<HomeFragment> weakReference;

        RefreshUploadHandler(HomeFragment fragment) {
            weakReference = new WeakReference<>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            HomeFragment mainFragment = weakReference.get();
            if (mainFragment != null && msg != null) {
                switch (msg.what) {
                    case 0:
                        //操作错误
                        mainFragment.refreshUpdateError();
                        break;
                    case 1:
                        // 1:开始导出
                        mainFragment.exportVideoStart(msg.getData());
                        break;
                    case 2:
                        //2 ：导出进度
                        mainFragment.refreshExportProgress(msg.arg1);
                        break;
                    case 3:
                        //3：导出成功
                        mainFragment.exportVideoEnd(msg.getData());
                        break;
                    case 4:
                        // 4：上传开始
                        break;
                    case 5:
                        //5：上传进度
                        mainFragment.refreshUploadProgress(msg.arg1);
                        break;
                    case 6:
                        // 6：上传完成
                        mainFragment.refreshUpdateFinish();
                        Message mMsg = this.obtainMessage();
                        mMsg.what = 7;
                        this.sendMessageDelayed(mMsg, 1000);
                        break;
                    case 7:
                        //上传完成后UI
                        mainFragment.refreshUpdateFinishUI();
                        break;
                }

            }
        }
    }

    //=================================上传信息===========================================
    @Override
    public void onSuccessUpload(UploadALiResultBean obj) {
        //更新进度
        if (RefreshUploadHandler != null) {
            Message msg = RefreshUploadHandler.obtainMessage();
            msg.what = 5;
            msg.arg1 = 1;
            RefreshUploadHandler.sendMessage(msg);
        }
        if (uploadType == 1) {
            //上传视频成功
            opusPublishRequestBean.setOpus_file_sign(obj.getmOssTokenResult().getFileInfo().getSign());
            opusPublishRequestBean.setOpus_path(obj.getmOssTokenResult().getFileInfo().getPath());
            //更新进度
            //上传图片
            if (!TextUtils.isEmpty(DyUIAPICallbackImpl.getInstance().getShortVideoFirstClipImgPath())) {
                uploadType = 2;
                uploadPresenter.getOSSTokenAndUploadInfo("opus", "jpg");
                uploadPresenter.setStrUploadPath(DyUIAPICallbackImpl.getInstance().getShortVideoFirstClipImgPath());
                GlideLoader.loadImage(DyUIAPICallbackImpl.getInstance().getShortVideoFirstClipImgPath(), iv_upload_icon);
            } else {
                //上传失败
                refreshUpdateError();
            }

        } else if (uploadType == 2) {
            //上传图片成功
            opusPublishRequestBean.setOpus_cover_sign(obj.getmOssTokenResult().getFileInfo().getSign());
            opusPublishRequestBean.setOpus_cover(obj.getmOssTokenResult().getFileInfo().getPath());
            //上传作品信息到服务器
            uploadType = 4;//业务操作
            uploadPresenter.submintOpusInfo(opusPublishRequestBean);
        } else if (uploadType == 3) {
            //动态图
        } else if (uploadType == 4) {
            //业务操作完成
            if (RefreshUploadHandler != null) {
                Message msg = RefreshUploadHandler.obtainMessage();
                msg.what = 6;
                RefreshUploadHandler.sendMessage(msg);
            }
        }

    }

    @Override
    public void onFailsUpload(UploadALiResultBean obj) {
        if (RefreshUploadHandler != null) {
            Message msg = RefreshUploadHandler.obtainMessage();
            msg.what = 0;
            RefreshUploadHandler.sendMessage(msg);
        }

    }

    @Override
    public void onExceptionUpload(UploadALiResultBean e) {

    }

    @Override
    public void onProgress(OSSRequest request, long currentSize, long totalSize) {
        if (uploadType == 1) {
            //上传视频的进度
        } else if (uploadType == 2) {
            //上传图片
        } else if (uploadType == 3) {
            //上传gift 的进度
        }
    }

    @Override
    public void onDestroy() {
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
        RxBus2.get().unRegister(this);
        super.onDestroy();
    }

    /**
     * 默认指定选中tab
     */
    @RxBusSubscribe(code = GlobalParams.EventType.TYPE_SHOW_MAIN_FIRST, threadMode = ThreadMode.MAIN)
    public void showTabsByIndex(Boolean iFlag) {
        KLog.i("=====收到消息：切换tab到最新");
        mbTopTabs.postDelayed(new Runnable() {
            @Override
            public void run() {
                onHomeClick();
                mbBottomTabs.setSelect(0);
                if (topTabPosition != 2) {
                    mbTopTabs.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            onLatestClick();
                            mbTopTabs.setSelect(2);
                        }
                    }, 30);
                }
            }
        }, 30);
    }
}
